package com.chang.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;

/**********************************************************************************************
 * 读取INI文件类
 * @author Sdav
 **********************************************************************************************/  
public class ReaderINI 
{  
	@SuppressWarnings("rawtypes")
	protected HashMap sections = new HashMap();  
    private transient String currentSecion;  
    private transient Properties current;  
    public ReaderINI(String filename) throws IOException 
    {  
        BufferedReader reader = new BufferedReader(new InputStreamReader(  
                new FileInputStream(filename), "utf-8"));  
        read(reader);  
        reader.close();  
    }  
  
    protected void read(BufferedReader reader) throws IOException 
    {  
        String line;  
        while ((line = reader.readLine())!=null ) 
        {  
            parseLine(line);  
        }  
          
    }  
  
    @SuppressWarnings("unchecked")
	protected void parseLine(String line)
    {  
        line = line.trim();  
        if (line.matches("\\[.*\\]")) 
        {  
            currentSecion = line.replaceFirst("\\[(.*)\\]", "$1");  
            current = new Properties();  
        } 
        else if (line.matches(".*=.*")) 
        {
            int i = line.indexOf('=');  
            String name = line.substring(0, i);  
            String value = line.substring(i + 1);  
            current.setProperty(name, value);  
            sections.put(currentSecion, current);  
        }  
    }  
  
    public String getValue(String section, String name) 
    {  
        Properties p = (Properties) sections.get(section);  
        if (p == null) {  
            return null;  
        }  
        String value = p.getProperty(name);  
        return value;  
    }  
  
}  